const FORMAT = require('../../api/util.js')
import API from '../../api/api.js'
import Dialog from '../../lib/vant-weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    readOnly: false,
    placeholder: '此为富文本编辑器，段落首行缩进系统会自动添加，可编辑标题、加粗、换行、插入图片等，开始输入信件内容...',
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,
    noticeShuJu: {
      tiMu:"",
      biMing: "苦海匿舟",
      neiRong: "",
      chuangJianShiJian: ""
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: "发送公告"
    })
    
    const that = this
    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({
      isIOS
    })
    
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const {
      windowHeight,
      platform
    } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({
      editorHeight,
      keyboardHeight
    })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const {
      statusBarHeight,
      platform
    } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    that.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {}
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {}
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },

  getImageInfo: function (path) {
    return new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: path,
        success(res) {
          resolve(res.type)
        },
        fail: err => {
          reject("获取数据出错了，请重试！")
          console.error(err)
        }
      })
    })
  },

  insertImage() {
    const that = this
    wx.chooseImage({
      count: 1,
      success: async function (res) {
        wx.showLoading({
          title: '正在加载...',
          mask: true
        })
        let type = ""
        await that.getImageInfo(res.tempFilePaths[0]).then(res => {
          type = res
        })
        let fileName = "noticeimages/" + new Date().getTime() + "." + type
        wx.cloud.uploadFile({
          cloudPath: fileName,
          filePath: res.tempFilePaths[0],
        }).then(res => {
          that.editorCtx.insertImage({
            src: res.fileID,
            width: '100%',
            success: function () {
              wx.hideLoading()
              wx.showToast({
                title: '图片插入成功！',
                icon: "success",
                duration: 2000
              })
            }
          })
        }).catch(error => {
          // handle error
        })
      }
    })
  },
  onFocus: function (e) {},
  onInput: function (e) {
    this.data.noticeShuJu.neiRong = e.detail.html
  },
  onTiMuInput: function (e) {
    this.data.noticeShuJu.tiMu = e.detail.value
  },
  onBlur: function (e) {},

  onFaBu: function (e) {
    const that = this
    let data = this.data.noticeShuJu
    let userInfo = wx.getStorageSync('userInfo')
    if (userInfo == "") {
      wx.showToast({
        title: '用户信息丢失，请重新登录。',
        icon: 'none'
      })
      return
    }
    data.type = "系统公告"
    data.chuangJianShiJian = FORMAT.formatDay(Math.floor(new Date().getTime() / 1000))
    let content = data.neiRong.replace(/<p/g, '<p style="text-indent: 1em;" ').replace(/<img/g, '<img style="text-indent: none !important;" ')
    data.neiRong = content
    Dialog.confirm({
        title: '发送公告',
        message: '请确定是否发送此公告？',
      })
      .then(() => {
        if (data.neiRong == "") {
          wx.showToast({
            title: '发送内容不能为空。',
            icon: 'none'
          })
          return
        }
        wx.showLoading({
          title: '加载中...',
          mask: true
        })
        API.tianJiaShuJu('systemnotices', data).then(res => {
          wx.hideLoading()
          wx.showToast({
            title: '公告发送成功！',
            icon: 'none',
            mask:true
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })
          }, 800)
        })
      })
      .catch(() => {
        wx.showToast({
          title: '已经取消发送。',
          icon: 'none'
        })
      })
  }
})